package com.xiangxiangjd.config.token;

import io.jsonwebtoken.*;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;

import java.util.Date;
import java.util.Map;

@Data
@ConfigurationProperties(value = "jwt.config")
public class JwtUtils {


    //签名私钥
    private String key;

    //签名的失效时间
    private Long ttl;

    /**
     * 颁发token
     *
     * @param id   用户ID
     * @param name 登录用户名
     * @param map
     * @return
     */
    public String createJwt(String id, String name, Map<String, Object> map) {


        //1.设置失效时间
        long now = System.currentTimeMillis();//当前毫秒数
        long exp = now + ttl;

        // 2.创建jwtBuilder
        JwtBuilder jwtBuilder = Jwts.builder().   //生存token
                setId(id). //id赋值
                setSubject(name).//用户
                setIssuedAt(new Date()). //存入时间
                signWith(SignatureAlgorithm.HS256, key);


        //3.更具map设置claims

        //map.entrySet()返回键值对   遍历键值对

        for (Map.Entry<String, Object> entry : map.entrySet()) {
            jwtBuilder.claim(entry.getKey(), entry.getValue());
        }


        jwtBuilder.setExpiration(new Date(exp));//失效时间
        // 4.创建token

        String token = jwtBuilder.compact();
        return token;
    }

    /**
     * 解析token
     */
    public Claims parseJwt(String token) {

        try {
            Claims claims = Jwts.parser().setSigningKey(key).//解析名字
                    parseClaimsJws(token).getBody();


            return claims;
            //捕捉过期token
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("token 过期");
            return null;
        }

    }

    public static void main(String[] args) {

        long now = System.currentTimeMillis();//当前毫秒数
        System.out.println(now);

    }


    /**
     * 验证jwt的有效期
     *
     * @param claims
     * @return
     */
    public static Boolean isTokenExpired(Claims claims) {
        final Date expiration = claims.getExpiration();
        return expiration.before(new Date());
    }
}
